A technical analysis of two big stocks - \(\textbf{Amazon and Ebay.}\)

\(\textbf{This is final project on Financial Analytics course.}\)

The aim of this project is to apply in practise tools for analyzing financial data. In this project, we used Random Walk theory for simulating prices, calculated stock returns, vizualized stock returns and calulated the correlation, found and vizualized moving avarage.

\(\textbf{Part 1.}\)

Installing all packages if needed

if (!require("quantmod") & !require("xts") & !require("rvest") & !require("stringr") & !require("forcats") & !require("lubridate") & !require("plotly") & !require("corrplot") & !require("dplyr") & !require("PerformanceAnalytics")) {
    library(quantmod)
    library(xts)
    library(rvest)
    library(stringr)
    library(plotly)
    library(corrplot)
    library(dplyr)
    library(PerformanceAnalytics)
    library(magrittr)
}
## Loading required package: quantmod
## Warning: package 'quantmod' was built under R version 3.5.2
## Loading required package: xts
## Loading required package: zoo
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
## Loading required package: TTR
## Version 0.4-0 included new data defaults. See ?getSymbols.
## Loading required package: rvest
## Warning: package 'rvest' was built under R version 3.5.2
## Loading required package: xml2
## Loading required package: stringr
## Warning: package 'stringr' was built under R version 3.5.2
## Loading required package: forcats
## Warning: package 'forcats' was built under R version 3.5.2
## Loading required package: lubridate
## 
## Attaching package: 'lubridate'
## The following object is masked from 'package:base':
## 
##     date
## Loading required package: plotly
## Loading required package: ggplot2
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
## Loading required package: corrplot
## corrplot 0.84 loaded
## Loading required package: dplyr
## Warning: package 'dplyr' was built under R version 3.5.2
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:lubridate':
## 
##     intersect, setdiff, union
## The following objects are masked from 'package:xts':
## 
##     first, last
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
## Loading required package: PerformanceAnalytics
## 
## Attaching package: 'PerformanceAnalytics'
## The following object is masked from 'package:graphics':
## 
##     legend

\(\textbf{Part 2.}\)

\(\textbf{Stock overal performance}\)

Amazon’s ticket symbol is AMZN and Ebay’s is EBAY

\(\textbf{All stock data we loaded from Yahoo Finance!}\)

source: https://finance.yahoo.com

We applied getSymbols function from quantmod package having three arguments (ticket symbol, time taken, source).

In this section we are getting two chart for both AMZN and EBAY. First one shows stock’s prices, second one is more complicated. It shows the Bollinger Band chart, % Bollinger change, Volume Traded and Moving Average Convergence Diverence in 2018 alone. Those charts are widely used in technical analysis of stocks, especially in measuring stock’s volatiliy.

The Volume chart shows how its stocks are traded on the daily.

The chartsare usually used to decide whether to buy/sell a stock.

\(\textbf{If it falls below the line, it is time to sell. If it rises above the line, it is experiencing an upward momentum.}\)

Brief explanation of what head(AMZN/EBAY) gives us:

Open is the price of the stock at the beginning of the trading day, high is the highest price of the stock on that trading day, low the lowest price of the stock on that trading day, and close the price of the stock at closing time. Volume indicates how many stocks were traded. Adjusted close is the closing price of the stock that adjusts the price of the stock for corporate actions.

We coclude that Ebay stock does not worth buying in 2018. Amazon stock is was worth buying from May till Oct 2018 (for more details look at charts). What happens in 2019? We consider that the trends will stay the same.

#start from 2018-01-01 til 2019
start <- as.Date("2018-01-01")
end <- as.Date("2019-10-01")

#getting stock data from yahoo
getSymbols("EBAY",from=start,to=end, src = "yahoo")
## 'getSymbols' currently uses auto.assign=TRUE by default, but will
## use auto.assign=FALSE in 0.5-0. You will still be able to use
## 'loadSymbols' to automatically load data. getOption("getSymbols.env")
## and getOption("getSymbols.auto.assign") will still be checked for
## alternate defaults.
## 
## This message is shown once per session and may be disabled by setting 
## options("getSymbols.warning4.0"=FALSE). See ?getSymbols for details.
## [1] "EBAY"
#Ebay's prices chart
EBAY%>%Ad()%>%chartSeries()

#Bollinger Band chart for Ebay
EBAY%>%chartSeries(TA='addBBands();addVo();addMACD()',subset='2018')

#getting stock data from yahoo
getSymbols("AMZN",from=start,to=end, src = "yahoo")
## [1] "AMZN"
#Amazon's prices chart
AMZN%>%Ad()%>%chartSeries()

#Bollinger Band chart for Amazon
AMZN%>%chartSeries(TA='addBBands();addVo();addMACD()',subset='2018')

#get first few rows
head(AMZN)
##            AMZN.Open AMZN.High AMZN.Low AMZN.Close AMZN.Volume
## 2018-01-02   1172.00   1190.00  1170.51    1189.01     2694500
## 2018-01-03   1188.30   1205.49  1188.30    1204.20     3108800
## 2018-01-04   1205.00   1215.87  1204.66    1209.59     3022100
## 2018-01-05   1217.51   1229.14  1210.00    1229.14     3544700
## 2018-01-08   1236.00   1253.08  1232.03    1246.87     4279500
## 2018-01-09   1256.90   1259.33  1241.76    1252.70     3661300
##            AMZN.Adjusted
## 2018-01-02       1189.01
## 2018-01-03       1204.20
## 2018-01-04       1209.59
## 2018-01-05       1229.14
## 2018-01-08       1246.87
## 2018-01-09       1252.70
head(EBAY)
##            EBAY.Open EBAY.High EBAY.Low EBAY.Close EBAY.Volume
## 2018-01-02     38.17     38.36    37.92      38.06     6997300
## 2018-01-03     37.99     39.28    37.90      39.22     9134400
## 2018-01-04     39.42     39.77    38.47      38.57     8958600
## 2018-01-05     38.85     39.84    38.81      39.69     7290400
## 2018-01-08     39.55     40.08    39.44      39.80     9714200
## 2018-01-09     40.10     40.13    39.48      39.53     6215900
##            EBAY.Adjusted
## 2018-01-02      37.91821
## 2018-01-03      39.07389
## 2018-01-04      38.42631
## 2018-01-05      39.54214
## 2018-01-08      39.65173
## 2018-01-09      39.38273

Another way of vizualization

Financial data is mostly plotted with a Japanese candlestick plot, so named because it was first created by 18th century Japanese rice traders. We applied the function candleChart() from quantmod to create such a chart. Also, Candlestick chats are widely used in technical analysis to make trading decisions.

for more details go here: https://plot.ly/r/candlestick-charts/

This r code gives us two charts all having two candlesticks - blue and red. First one indicates a day where the closing price was higher than the open, another - day where the open was higher than the close.

candleChart(AMZN, up.col = "blue", dn.col = "red", theme = "white")

candleChart(EBAY, up.col = "blue", dn.col = "red", theme = "white")

\(\textbf{Below, we plot AMZN's and EBAY's adjusted close together.}\)

We initialize xts object from quantmod containing stock prices for AMZN and EBAY.

Then, we create a plot using zoo method which allows for multiple series be ploted on the same plot.

stocks <- as.xts(data.frame(AMZN = AMZN[, "AMZN.Close"], EBAY = EBAY[, "EBAY.Close"]))
head(stocks)
##            AMZN.Close EBAY.Close
## 2018-01-02    1189.01      38.06
## 2018-01-03    1204.20      39.22
## 2018-01-04    1209.59      38.57
## 2018-01-05    1229.14      39.69
## 2018-01-08    1246.87      39.80
## 2018-01-09    1252.70      39.53
plot(as.zoo(stocks[, c("AMZN.Close")]))
par(new = TRUE)

plot(as.zoo(stocks[, "EBAY.Close"]), screens = 1, lty = 3, xaxt = "n", yaxt = "n", 
    xlab = "", ylab = "")

mtext("Price", side = 4, line = 3)

#adding legend to plot
legend("topleft", c("AMZN", "EBAY"), lty = 1:3, cex = 0.5)

\(\textbf{Part 3.}\)

\(\textbf{Visualization of a Correlation Matrix}\)

To successfully purchase a stock, we should take into account correlation (the smaller correlation is, the more bigger is rate of return).

\(\textbf{A rule of thumb: do not put all your eggs in one basket!}\)

Since, AMZN and EBAY are stocks from different sectrors, therefore the correlation is small.

Investing money in stocks from different sectros minimizes the risk.

#merging two data frames together
data<-cbind(diff(log(Cl(EBAY))),diff(log(Cl(AMZN))))

#getting chart with correlation data
chart.Correlation(data)

\(\textbf{Amazon and Ebay stocks returns}\)

To do that, we need to use apply function which transforms our data into appropriate type. We calculate the returns in certain period: \(return_{t, 0} = \frac{price_t}{price_0}\)

The plot shows us the profitability of each stocks. It seen clearly seen in the plot that two stocks are not correlated what we’ve already shown in previuos section. Amazon stock is much more profitable than Ebay.

In addition, we could also calculate and vizualize stock changes.

\(change_t = log(price_t) - log(price_{t - 1})\) t - period of time.

#getting stock returns
stock_returns = apply(stocks, 1, function(x) {x / stocks[1,]}) %>% 
                                            t %>% as.xts

#getting stock change using diff function
stock_change = diff(log(stock_returns[, ]))

#heading data
head(stock_change)
##             AMZN.Close   EBAY.Close
## 2018-01-02          NA           NA
## 2018-01-03 0.012694369  0.030022958
## 2018-01-04 0.004466026 -0.016712074
## 2018-01-05 0.016033319  0.028624469
## 2018-01-08 0.014321657  0.002767646
## 2018-01-09 0.004664776 -0.006807035
head(stock_returns)
##            AMZN.Close EBAY.Close
## 2018-01-02   1.000000   1.000000
## 2018-01-03   1.012775   1.030478
## 2018-01-04   1.017308   1.013400
## 2018-01-05   1.033751   1.042827
## 2018-01-08   1.048662   1.045717
## 2018-01-09   1.053566   1.038623
plot(as.zoo(stock_returns), screens = 1, lty = 1:3, xlab = "Date", ylab = "Return", main = "Amazon and Ebay stock returns")

legend("topleft", c("AMZN", "EBAY"), lty = 1:3, cex = 0.5)

plot(as.zoo(stock_change), screens = 1, lty = 1:3, xlab = "Date", ylab = "Log Difference", main = "Amazon and Ebay stock change")

legend("topleft", c("AMZN", "Ebay"), lty = 1:3, cex = 0.5)

\(\textbf{Moving Avarages}\)

Moving avarages smooth a series and help find trends in stocks. They do not predict price direction, but rather define the current direction. Most moving averages are based on closing prices.

There two types of Moving avarages - Simple and Exponential. Simple one calculates the avarage price over certain periods of time. Exponential - reduce the lag by applying more weight to recent prices.

\(MA^q_t = \frac{1}{q}\sum_{i=0}{q - 1}x_{t-i}\)

start = as.Date("2018-01-01")
getSymbols(c("AMZN", "EBAY"), src = "yahoo", from = start, to = end)
## [1] "AMZN" "EBAY"
candleChart(AMZN, up.col = "black", dn.col = "red", theme = "white", subset = "2018-01-01/", ad)

#adding MA via addSMA from quantmod
addSMA(n = 20)

addEMA(n = 20)

candleChart(EBAY, up.col = "black", dn.col = "red", theme = "white", subset = "2018-01-01/")

addSMA(n = 20)

addEMA(n = 20)

\(\textbf{Part 6}\)

Logreturns and vizualization of risk vs reward

We applied plotly to create a visualization of each stock’s risk vs reward.

Risk: standard deviation of log returns.

Reward: mean of log returns.

#Loads the company stock using ticker
getSymbols("AMZN",from="2008-08-01",to="2018-08-20")
## [1] "AMZN"
getSymbols("EBAY",from="2008-08-01",to="2018-08-20")
## [1] "EBAY"
#Stock returns in log
AMZN_log_returns<-AMZN%>%Ad()%>%dailyReturn(type='log')
EBAY_log_returns<-EBAY%>%Ad()%>%dailyReturn(type='log')

#Mean of log stock returns 
AMZN_mean_log<-mean(AMZN_log_returns)
EBAY_mean_log<-mean(EBAY_log_returns)

#standard deviation of log stock returns
AMZN_sd_log<-sd(AMZN_log_returns)
EBAY_sd_log<-sd(EBAY_log_returns)

mean_log<-c(AMZN_mean_log,EBAY_mean_log)
sd_log<-c(AMZN_sd_log,EBAY_sd_log)

#create data frame
graph1<-data.frame(rbind(c("AMZN",AMZN_mean_log, AMZN_sd_log), c("EBAY",EBAY_mean_log,EBAY_sd_log), stringsAsFactors = FALSE))

graph1<-data.frame(mean_log, sd_log)
rownames(graph1)<-c("AMZN","EBAY")
colnames(graph1)<-c("AMZN_log_returns", "EBAY_log_returns")

xlab<-list(title="Reward")
ylab<-list(title="Risk")

plot_ly(x=graph1[,1],y=graph1[,2],text=rownames(graph1),type='scatter',mode="markers",marker=list(color=c("black","blue")))%>%layout(title="Risk vs Reward",xaxis=xlab,yaxis=ylab)

\(\textbf{Part 7}\)

Random Walk for prices simulation of Amazon stock

The random walk theory suggests that changes in stock prices have the same distribution (normal) and are independent of each other, therefore, the past movement or trend of a stock price or market cannot be used to predict its future movement.

testsim<-rep(NA,500)

#generate random daily exponent increase rate using AMZN's mean and sd log returns

#one year 252 trading days, simulate for 2 years 
# 2*252 trading days

AMZN_prices<-rep(NA,252*2)

#most recent price
AMZN_prices[1]<-as.numeric(AMZN$AMZN.Adjusted[length(AMZN$AMZN.Adjusted),])

#start simulating prices

for(i in 2:500){
  #generates multivariate normal random variates in the space
  AMZN_prices[i]<-AMZN_prices[i-1]*exp(rnorm(1,AMZN_mean_log,AMZN_sd_log))
}

#creating a frame
random_data<-cbind(AMZN_prices,1:(252*2))
colnames(random_data)<-c("Price","Day")
random_data<-as.data.frame(random_data)

random_data%>%ggplot(aes(Day,Price))+geom_line()+labs(title="Amazon (AMZN) price simulation for 2 years")+theme_bw()
## Warning: Removed 4 rows containing missing values (geom_path).

#ending session
sessionInfo()
## R version 3.5.1 (2018-07-02)
## Platform: x86_64-apple-darwin15.6.0 (64-bit)
## Running under: macOS  10.14.4
## 
## Matrix products: default
## BLAS: /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libRblas.0.dylib
## LAPACK: /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libRlapack.dylib
## 
## locale:
## [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] PerformanceAnalytics_1.5.2 dplyr_0.8.0.1             
##  [3] corrplot_0.84              plotly_4.9.0              
##  [5] ggplot2_3.1.0              lubridate_1.7.4           
##  [7] forcats_0.4.0              stringr_1.4.0             
##  [9] rvest_0.3.3                xml2_1.2.0                
## [11] quantmod_0.4-14            TTR_0.23-4                
## [13] xts_0.11-2                 zoo_1.8-4                 
## 
## loaded via a namespace (and not attached):
##  [1] tidyselect_0.2.5  purrr_0.2.5       lattice_0.20-35  
##  [4] colorspace_1.3-2  htmltools_0.3.6   viridisLite_0.3.0
##  [7] yaml_2.2.0        rlang_0.3.4       pillar_1.3.1     
## [10] later_0.8.0       glue_1.3.0        withr_2.1.2      
## [13] plyr_1.8.4        munsell_0.5.0     gtable_0.2.0     
## [16] htmlwidgets_1.3   evaluate_0.12     labeling_0.3     
## [19] knitr_1.20        httpuv_1.5.1      crosstalk_1.0.0  
## [22] curl_3.2          Rcpp_1.0.0        xtable_1.8-3     
## [25] scales_1.0.0      backports_1.1.2   promises_1.0.1   
## [28] jsonlite_1.6      mime_0.6          digest_0.6.18    
## [31] stringi_1.2.4     shiny_1.3.2       grid_3.5.1       
## [34] rprojroot_1.3-2   quadprog_1.5-5    tools_3.5.1      
## [37] magrittr_1.5      lazyeval_0.2.1    tibble_2.1.1     
## [40] crayon_1.3.4      tidyr_0.8.2       pkgconfig_2.0.2  
## [43] data.table_1.12.2 assertthat_0.2.0  rmarkdown_1.10   
## [46] httr_1.4.0        R6_2.3.0          compiler_3.5.1

\(\textbf{Conclusion:}\) Investing in stock market is not so easy as it seems to be. The probability of losing money is high, because many investors do not pay attention to risk. But with such tools like Random Walk and Moving Avarage chart, we can avoid risk and invest in stock successfully. Only being familiar with financial analysis rools will help us make right decisions.

References: https://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:moving_averages https://thebusinessprofessor.com/knowledge-base/random-walk-theory-stock-market-explained/ https://cran.r-project.org/web/packages/magrittr/vignettes/magrittr.html https://towardsdatascience.com/analyzing-stocks-using-r-550be7f5f20d https://ntguardian.wordpress.com/2017/04/03/introduction-stock-market-data-r-2/ https://ntguardian.wordpress.com/2017/03/27/introduction-stock-market-data-r-1/